import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import '../utils/util.dart';
import '../models/song.dart';

class HistoryService {
  static const String _historyKey = 'play_history';
  static const int _maxHistorySize = 100;
  
  // 历史记录改变的回调函数列表
  static final List<VoidCallback> _listeners = [];
  
  /// 添加监听器
  static void addListener(VoidCallback listener) {
    _listeners.add(listener);
  }
  
  /// 移除监听器
  static void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
  }
  
  /// 通知所有监听器
  static void _notifyListeners() {
    for (final listener in _listeners) {
      listener();
    }
  }

  /// 添加歌曲到播放历史
  static Future<void> addToHistory(Song song) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final historyJson = prefs.getStringList(_historyKey) ?? [];

      // 构建当前歌曲的Map，并尝试下载缓存到本地
      final Map<String, dynamic> currentMap = song.toJson();
      //歌曲缓存功能，耗费流量，选择屏蔽
      // try {
      //   if (song.audioUrl != null && song.audioUrl!.isNotEmpty &&
      //       song.audioUrl!.toLowerCase().startsWith('http')) {
      //     final safeName = '${song.name}'.replaceAll(RegExp(r'\s+'), '_');
      //     final localPath = await CommonUtils.downloadFile(
      //       song.audioUrl!,
      //       persistent: true,
      //       fileName: '$safeName.mp3',
      //       subDir: 'history_cache',
      //     );
      //     currentMap['cached_audio_path'] = localPath;
      //   }
      // } catch (e) {
      //   // 下载失败不影响历史记录保存
      // }

      // 读取历史并保持已有扩展字段
      List<Map<String, dynamic>> historyMaps = historyJson
          .map((json) => Map<String, dynamic>.from(jsonDecode(json)))
          .toList();

      // 移除重复项
      historyMaps.removeWhere((m) {
        final id = (m['id'] ?? m['url_id'] ?? '').toString();
        final source = (m['source'] ?? '').toString();
        return id == song.effectiveId && source == song.source;
      });

      // 插入到开头
      historyMaps.insert(0, currentMap);

      // 限制数量
      if (historyMaps.length > _maxHistorySize) {
        historyMaps = historyMaps.take(_maxHistorySize).toList();
      }

      await prefs.setStringList(
        _historyKey,
        historyMaps.map((m) => jsonEncode(m)).toList(),
      );
      
      // 通知监听器
      _notifyListeners();
    } catch (e) {
      print('Error adding to history: $e');
    }
  }

  /// 获取播放历史
  static Future<List<Song>> getHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final historyJson = prefs.getStringList(_historyKey) ?? [];
      var list = <Song>[];
      for (final entry in historyJson) {
        final map = Map<String, dynamic>.from(jsonDecode(entry));
        final song = Song.fromJson(map);
        final cached = (map['cached_audio_path'] ?? '').toString();
        if (cached.isNotEmpty) {
          song.audioUrl = cached;
        }
        list.add(song);
      }
      if (list.length > _maxHistorySize) {
        list = list.take(_maxHistorySize).toList();
        final trimmed = list.map((song) => jsonEncode(song.toJson())).toList();
        await prefs.setStringList(_historyKey, trimmed);
      }
      return list;
    } catch (e) {
      print('Error getting history: $e');
      return [];
    }
  }

  /// 清空播放历史
  static Future<void> clearHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_historyKey);
      try {
        // 清空持久缓存目录
        final baseDir = await getApplicationDocumentsDirectory();
        final dir = Directory('${baseDir.path}/history_cache');
        if (await dir.exists()) {
          await dir.delete(recursive: true);
        }
      } catch (_) {}
      
      // 通知监听器
      _notifyListeners();
    } catch (e) {
      print('Error clearing history: $e');
    }
  }

  /// 从历史记录中移除指定歌曲
  static Future<void> removeFromHistory(Song song) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final historyJson = prefs.getStringList(_historyKey) ?? [];
      List<Map<String, dynamic>> historyMaps = historyJson
          .map((json) => Map<String, dynamic>.from(jsonDecode(json)))
          .toList();

      // 找到并删除对应缓存文件
      final index = historyMaps.indexWhere((m) {
        final id = (m['id'] ?? m['url_id'] ?? '').toString();
        final source = (m['source'] ?? '').toString();
        return id == song.effectiveId && source == song.source;
      });
      if (index != -1) {
        final map = historyMaps[index];
        final candidatePaths = <String>{};
        final p1 = (map['cached_audio_path'] ?? '').toString();
        if (p1.isNotEmpty) candidatePaths.add(p1);
        final p2 = (song.audioUrl ?? '').toString();
        if (p2.isNotEmpty && !p2.toLowerCase().startsWith('http')) candidatePaths.add(p2);

        for (final p in candidatePaths) {
          try {
            final f = File(p);
            if (await f.exists()) {
              await f.delete();
            }
          } catch (_) {}
        }

        historyMaps.removeAt(index);
      }

      await prefs.setStringList(
        _historyKey,
        historyMaps.map((m) => jsonEncode(m)).toList(),
      );
      
      // 通知监听器
      _notifyListeners();
    } catch (e) {
      print('Error removing from history: $e');
    }
  }
}
